<script>
import deviceForm from '../../components/device/deviceForm.vue'
import DeviceApi from '../../api/device'
export default {
  components: {
    deviceForm,// 引入表单组件
  },
  data() {
    return {
      device: {},// 设备数据
      isNotFetch: true, // 是否允许获取数据
    }
  },
  methods: {
    // 从厦门大学平台获取设备信息
    async fetchXiamen() {
      try {
        let xiamenId = this.device.xiamenId
        console.log(xiamenId)
        this.device = {}
        const api = new DeviceApi()
        // 检查设备是否已存在
        let res1 = await api.findByXiamenId(xiamenId)
        if (res1.data.id) {
          this.$myMessageBox(`《${res1.data.title}》该设备已存在，请勿重复添加！`)
          this.$router.push({ name: 'device-detail', params: { id: res1.data.id } })
        } else {
          // 获取新设备信息
          let res2 = await api.fetchXiamen(xiamenId)
          console.log(res2)
          this.$myMessageBox(res2.msg)
          if (res2.code === 400) {
            this.device = {}
            this.isNotFetch = true
          } else {
            this.device = res2.data
            console.log(this.device)
          }
        }
      } catch (err) {
        console.error(err)
        this.$myMessageBox('应用服务器访问错误！')
      }
    },
    // 保存设备信息
    async deviceSave() {
      if (this.device.title && this.device.xiamenId) {
        try {
          const api = new DeviceApi()
          let res = await api.add(this.device)
          console.log(res)
          if (res.code === 201) {
            this.$myMessageBox(res.msg)
            this.$router.push({ name: 'device-list' })
          }
        } catch (err) {
          console.error(err)
          this.$myMessageBox('应用服务器访问错误！')
        }
      } else {
        this.$myMessageBox('设备名称与Id号信息不完整！')
      }
    },
  },
  watch: {
    device: {
      handler(newValue) {
        let xiamenId = newValue.xiamenId
        let regex4 = /^7\d{3}$/ // 匹配4位数字且第一位为7

        if (xiamenId) {
          if (xiamenId.length === 4 && regex4.test(xiamenId)) {
            this.isNotFetch = false
          } else {
            this.isNotFetch = true
          }
        }
      },
      deep: true,
    },
  },
}
</script>

<template>
  <div class="device-add w80">
    <div class="header">
      <h2>新增设备</h2>
      <p>
        <a
          class="button"
          :class="{ disabled: isNotFetch }"
          href="javascript:void(0)"
          @click="fetchXiamen"
          >从厦门大学贵重仪器共享平台采集设备信息</a
        >
        <a class="button" href="javascript:void(0)" @click="$goBack">返回</a>
      </p>
    </div>
    <div class="block">
      <device-form v-model="device" @device-save="deviceSave"></device-form>
    </div>
  </div>
</template>

<style scoped></style>
